import axios from 'axios'
import Mgr from './SecurityService'
import store from '@/store'
let manager = new Mgr(),
	Token = '',
	org_code = null

org_code = store.getters.org_code

manager.getRole().then(function (item) {
	console.log(item)
	if (item) {
		Token = item
		// 获取org_code
		if (item.profile.inst_code) {
			// org_code = item.profile.inst_code
			console.log(org_code)
			org_code = 2470
		}
		else {
			org_code = store.getters.org_code
		}
	}
})

axios.defaults.baseURL = configUrl.apiUrl + '/api-idcas/'
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.withCredentials = true

const service = axios.create({})
// 机构管理配置
service.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8'
// request interceptor
service.interceptors.request.use(
	(config) => {
		let str = config.url.slice(0, 4)
		if (str === '/api') {
			config.baseURL = configUrl.apiUrl
		}
		else {
			config.baseURL = configUrl.apiUrl + '/api-idcas/'
		}
		config.headers.SystemId = 1
		if (Token) {
			config.headers.common.Authorization = Token.token_type + ' ' + Token.access_token
		}
		else {
			manager.signIn({ state: window.location.href })
		}
		// 统一配置org_code
		if (config.method === 'post') {
		}
		else if (config.method === 'get') {
			config.params = {
				org_code: org_code,
				...config.params
			}
		}

		// return config
		config.headers.SystemId = JSON.parse(localStorage.getItem('org_msg')).symelid
		return new Promise((resolve) => {
			var manager = new Mgr()
			manager.getRole().then(function (item) {
				if (item) {
					sessionStorage.setItem('loginInfo', JSON.stringify(item))
					config.headers.common.Authorization = item.token_type + ' ' + item.access_token
				}
				else {
					manager.signIn()
				}
				resolve(config)
			})
		})
	},
	(error) => {
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	(response) => {
		const res = response.data
		return res
	},
	(error) => {
		// console.log(`err${error}`) // for debug
		return Promise.reject(error)
	}
)

export default service
